require"luacalc"

open"../sud.csv"
--save"../sudoku.csv"

for i = 1 , 9 do
	set(i,10, "=LEFT(SELECT(1, $x, 9, $x))")
end

for i = 1, 9 do
	set(10,i, "=LEFT(SELECT($y, 1, $y, 9))")
end

set(11, 1, "=LEFT(A1:C3)")
set(11, 2, "=LEFT(D1:F3)")
set(11, 3, "=LEFT(G1:I3)")
set(12, 1, "=LEFT(A4:C6)")
set(12, 2, "=LEFT(D4:F6)")
set(12, 3, "=LEFT(G4:I6)")
set(13, 1, "=LEFT(A7:C9)")
set(13, 2, "=LEFT(D7:F9)")
set(13, 3, "=LEFT(G7:I9)")

local ind = luacalc.index_to_string
for i=1, 9 do
	for j = 1, 9 do
		local s = "=IF(ISEMPTY("..luacalc.index_to_string(i)..j.."), SAME("..ind(i).."10,"..ind(math.ceil(i/3))..(math.ceil(j/3) + 10)..", J"..j.."), '')"
		set(j+13, i, s)
		print(j+13, i, s)
		
	end
end

function basic_solve()

	local retry = true
	-- loop while there may be more cells
	while retry do
		retry = false
		
		for i=1, 9 do
			for j = 1, 9 do
				local s = get(i, j+13)
				if string.len(s)==1 then
					print("solved!", s, i , j)
					local cell = ind(i)..j
					print("bef", cell, _G[cell]) 
					set(j, i, s)
					print("aft", cell, _G[cell]) 
					retry = true
					
				end
			--	print(j+13, i, s)
				
			end
		end
	
	end

end

basic_solve()


function next_solve()
	string.foreach(_G["A11"], function(val)
		for i=1, 3 do
			for j = 1, 3 do
				print(i, j, val)
			end
		end
	end)
end

next_solve()

save"initialres.csv"